package cmd

import (
	"fmt"
	"os"

	"github.com/louloulin/dataflare/pkg/workflow"
	"github.com/louloulin/dataflare/pkg/workflow/validator"
	"github.com/spf13/cobra"
)

var (
	workflowFile string
	verbose      bool
)

// validateCmd represents the validate command
var validateCmd = &cobra.Command{
	Use:   "validate",
	Short: "Validate a workflow definition",
	Long: `Validate a workflow definition file for syntax and semantic errors.

This command checks a workflow definition file for syntax errors, missing
required fields, invalid configurations, and other issues that would prevent
the workflow from being deployed successfully.

Example:
  dataflare validate --file workflow.yaml
  dataflare validate --file workflow.json --verbose`,
	RunE: func(cmd *cobra.Command, args []string) error {
		// Check if workflow file is provided
		if workflowFile == "" {
			return fmt.Errorf("workflow file is required")
		}

		// Read workflow file
		data, err := os.ReadFile(workflowFile)
		if err != nil {
			return fmt.Errorf("failed to read workflow file: %w", err)
		}

		// Create validator
		v := validator.NewWorkflowValidator()

		// Validate workflow
		result, err := v.ValidateWorkflowDefinition(data)
		if err != nil {
			return fmt.Errorf("failed to validate workflow: %w", err)
		}

		// Print validation result
		if result.Valid {
			fmt.Println("Workflow definition is valid.")
			if verbose {
				// Parse workflow definition
				definition, err := workflow.ParseDefinition(data)
				if err != nil {
					return fmt.Errorf("failed to parse workflow definition: %w", err)
				}

				// Print workflow details
				fmt.Printf("\nWorkflow Details:\n")
				fmt.Printf("  Name: %s\n", definition.Name)
				fmt.Printf("  Description: %s\n", definition.Description)
				fmt.Printf("  Version: %s\n", definition.Version)
				fmt.Printf("  Sources: %d\n", len(definition.Sources))
				fmt.Printf("  Processors: %d\n", len(definition.Processors))
				fmt.Printf("  Sinks: %d\n", len(definition.Sinks))
				fmt.Printf("  Edges: %d\n", len(definition.Edges))
			}
		} else {
			fmt.Println("Workflow definition is invalid:")
			for _, issue := range result.Issues {
				fmt.Printf("  - %s\n", issue)
			}
			return fmt.Errorf("workflow validation failed")
		}

		return nil
	},
}

func init() {
	rootCmd.AddCommand(validateCmd)

	// Add flags
	validateCmd.Flags().StringVarP(&workflowFile, "file", "f", "", "Workflow definition file")
	validateCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
}
